package com.example.todolist.service;

import com.example.todolist.entity.Habit;
import com.example.todolist.mapper.HabitMapper;
import com.example.todolist.tools.ResponseBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.List;
import java.util.Objects;

@Service
public class HabitService {
    @Autowired
    private HabitMapper habitMapper;
    public String getWeekDay(Date date)
    {
        Calendar c=Calendar.getInstance();
        c.setTime(date);
        int weekday=c.get(Calendar.DAY_OF_WEEK);
        switch (weekday)
        {
            case 1: return "DAY7";
            case 2: return "DAY1";
            case 3: return "DAY2";
            case 4: return "DAY3";
            case 5: return "DAY4";
            case 6: return "DAY5";
            case 7: return "DAY6";
            default: return null;
        }
    }
    public ResponseBody<Integer> insertHabit(Habit habit) {
        if(habit.getBeginDate()==null)
        {
            habit.setBeginDate(Date.valueOf(LocalDate.now()));
        }
        habit.setLastDays(0);
        return new ResponseBody<>(200,"success",habitMapper.insertHabit(habit));
    }

    public Integer checkForHabit(Integer userId, Integer habitId) {
        Date date=Date.valueOf(LocalDate.now());
        String weekDay = getWeekDay(date);
        Habit habit = habitMapper.getHabit(userId,habitId);
        Integer status = habitMapper.getWeekStatus(userId,habitId,weekDay);
        if(status!=null&&status==1)
        {
            return 0;
        }
        Integer lastDays = habit.getLastDays()+1;
        habitMapper.setLastDays(userId,habitId,lastDays);
        return habitMapper.setForHabit(userId,habitId,weekDay,1);
    }

    public List<Habit> getAllHabit(Integer userId)
    {
        return habitMapper.getAllHabit(userId);
    }

    public void setHabit(Integer userId,Integer habitId)
    {
        Date date=Date.valueOf(LocalDate.now());
        String weekDay = getWeekDay(date);
        if(Objects.equals(weekDay, "DAY1"))
        {
            Habit habit1 = habitMapper.getHabit(userId,habitId);
            habitMapper.deleteHabit(userId,habitId);
            Habit habit2=new Habit();
            habit2.setHabitName(habit1.getHabitName());
            habit2.setBeginDate(habit1.getBeginDate());
            habit2.setHabitId(habitId);
            habit2.setUserId(userId);
            habit2.setLastDays(habit1.getLastDays());
            habitMapper.insertHabit(habit2);
        }
        habitMapper.setForHabit(userId,habitId,weekDay,0);
    }
}
